using System;
using System.Windows.Input;

using EMan.BL.Commands;
using EMan.Interface.Common;
using EMan.Interface.EntityEditing;

using TrueCode.Core.Aspects;
using TrueCode.Core.Diagnostics;
using TrueCode.Core.EditableEntity;

namespace EMan.BL.EntityEditing
{
  public abstract class EntityEditorPresenter< TView > : Presenter< TView >, IEntityEditorPresenter< TView > where TView : class, IEntityEditorView
  {
    protected readonly SimpleCommand OkCommand;
    private readonly SimpleCommand _cancelCommand;

    protected EntityEditorPresenter( [NotNull] IDiagnostic diagnostic ) : base( diagnostic )
    {
      OkCommand = new SimpleCommand(Submit, false);
      _cancelCommand = new SimpleCommand( Cancel );
    }

    public bool Submited{ get; private set; }

    ICommand IEntityEditorPresenter.OkCommand
    {
      get { return OkCommand; }
    }

    ICommand IEntityEditorPresenter.CancelCommand
    {
      get { return _cancelCommand; }
    }

    private void Submit()
    {
      Submited = true;
      View.Submitted = true;
      View.Close();
    }

    private void Cancel()
    {
      View.Submitted = false;
      View.Close();
    }
  }

  public abstract class EntityEditorPresenter : EntityEditorPresenter< IEntityEditorView >, ISimpleEntityEditorPresenter
  {
    protected EntityEditorPresenter( [NotNull] IDiagnostic diagnostic ) : base( diagnostic ){}
  }

  public abstract class NewEnitytEditorPresenter<TEditable> : Presenter<IEntityEditorView>, IEntityEditorPresenter<IEntityEditorView> where TEditable : class, IEditableEntity
  {
    private readonly TEditable _editable;
    private readonly SimpleCommand _okCommand;
    private readonly SimpleCommand _cancelCommand;

    protected NewEnitytEditorPresenter( [NotNull] TEditable editable, [NotNull] IDiagnostic diagnostic ) : base( diagnostic )
    {
      if( editable == null ) throw new ArgumentNullException( "editable" );

      _editable = editable;
      _okCommand = new SimpleCommand(Submit, false);
      _cancelCommand = new SimpleCommand( Cancel );
    }

    ICommand IEntityEditorPresenter.OkCommand
    {
      get { return OkCommand; }
    }

    ICommand IEntityEditorPresenter.CancelCommand
    {
      get { return _cancelCommand; }
    }

    protected SimpleCommand OkCommand
    {
      get { return _okCommand; }
    }


    private void Submit()
    {
      View.Submitted = true;
      View.Close();
      _editable.AcceptChanges();
    }

    private void Cancel()
    {
      _editable.RejectChanges();
      View.Submitted = false;
      View.Close();
    }
  }
}